//
//  MoreTableViewController.m
//  FreeReading
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "MoreTableViewController.h"
#import "EnjoyDetailViewController.h"
#import "CategoryModel.h"
#import "EnjoyCell.h"

@interface MoreTableViewController ()
{
    NSString *_next_url;
    BOOL _isHeaderRefresh;
    UILabel *titleLabel;
}
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation MoreTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;

    }
    
    [self setSubviews];
   
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"EnjoyCell" bundle:nil] forCellReuseIdentifier:@"EnjoyCell"];
    
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableView.header beginRefreshing];
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

#pragma mark - 拉动刷新方法
- (void)loadNewData
{
    _isHeaderRefresh = YES;
    [self loadData];
}

- (void)loadMoreData
{
    _isHeaderRefresh = NO;
    [self loadData];
    
}

// 设置UI
- (void)setSubviews
{
    self.tableView.showsVerticalScrollIndicator = NO;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBar"] forBarMetrics:(UIBarMetricsDefault)];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    // titleView
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = self.titles;
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    // UIBarButtonItem
    UIBarButtonItem *leftbarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-arrowleft"] style:(UIBarButtonItemStylePlain) target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = leftbarButton;
    
}
#pragma mark - 返回上一页
- (void)back:(UIBarButtonItem *)button
{
 
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 加载数据
- (void)loadData
{
    
    
    // 判断网络状态
    AFNetworkReachabilityManager *net_manager = [AFNetworkReachabilityManager sharedManager];
    [net_manager startMonitoring];
    [net_manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"网络异常 请检查网络后再试" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                return ;
                
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
    }];
    
    
    
    if (_isHeaderRefresh == YES) {
        _next_url = self.url;
    } else {
        
    }

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 如果下一页连接为空 提示已加载所有数据
    if ([_next_url isEqualToString:@""]) {
        
        [self.tableView.footer noticeNoMoreData];
        return;
    }
    
    [manager GET:_next_url parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
    _next_url = responseObject[@"data"][@"info"][@"next_url"];

        NSArray *dataArr = responseObject[@"data"][@"weekends"];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dic in dataArr) {
            
            CategoryModel *model = [[CategoryModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [tempArray addObject:model];
        }
        
        if (_isHeaderRefresh) {
            self.dataArray = tempArray;
            [self.tableView.header endRefreshing];
            [self.tableView reloadData];
        } else {
            [self.dataArray addObjectsFromArray:tempArray];
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
        }
    
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
       
        
        NSString *message = [NSString stringWithFormat:@"%@", [error localizedDescription]];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            return ;
        }];
        
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];

    }];
    
    
}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([self isViewLoaded] && self.view.window == nil) {
        
        self.view = nil;
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CategoryModel *model = self.dataArray[indexPath.row];
         EnjoyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EnjoyCell" forIndexPath:indexPath];
        
        cell.categoryModel = model;
        return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 280;
}

#pragma mark - cell点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CategoryModel *model = self.dataArray[indexPath.row];
    
    EnjoyDetailViewController *detailVC = [[EnjoyDetailViewController alloc] init];
    detailVC.url = model.detailUrl;
    detailVC.newsTitle = model.title;
    detailVC.pic_url = model.pic_url;
    detailVC.tag = @"1";
    [self.navigationController pushViewController:detailVC animated:YES];
}
#pragma mark - 懒加载
-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    
    return _dataArray;
}

@end
